#include "home.h"
#include "ui_home.h"

Home::Home(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Home)
{
    ui->setupUi(this);

    usocket= new QUdpSocket(this);
    usocket->bind(QHostAddress::AnyIPv4,8889);

    connect(ui->sousuo,SIGNAL(clicked()),this,SLOT(udpconnect()));
    connect(usocket,SIGNAL(readyRead()),this,SLOT(udpread_data()));
    //connect(ui->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(tcpconnect(QListWidgetItem*)));
    connect(ui->lianjie,SIGNAL(clicked()),this,SLOT(tcpconnect()));
    connect(ui->comboBox,SIGNAL(activated(QString)),SLOT(act(QString)));
    heartbeatTimer = new QTimer(this);
    responseTimer = new QTimer(this);
    connect(heartbeatTimer, &QTimer::timeout,this, &Home::sendHeartbeat);
    connect(responseTimer, &QTimer::timeout, this, &Home::onNoResponse);


}
//void Home::paintEvent(QPaintEvent *event)
//{
//    QPainter painter(this);
//    QPixmap map(":/new/prefix1/bejing.jpg");
//    painter.drawPixmap(0,0,this->width(),this->height(),map);
//}
//数据传输交互
void Home::xinxijiaohu()
{
    if(da.type==1&&da.up_config==true)
    {
        QFileInfo fileInfo(":/new/prefix1/five.json");
        qint64 fileSize=fileInfo.size();
        QString  text = fileInfo.baseName();
        da.sj.file_len=fileSize;
        da.sj.file_name=text;
        QJsonObject json;
        json.insert("type",2);
        QJsonObject item;
        item.insert("flag","start");
        item.insert("file_name",da.sj.file_name);
        item.insert("file_len",da.sj.file_len);
        json.insert("data",QJsonValue(item));
        QJsonDocument document;
        document.setObject(json);
        QByteArray byte_array = document.toJson(QJsonDocument::Compact);
        tsocket->write(byte_array);

    }
    if(da.type==2&&da.sj.flag=="start")
    {
        QString text=ui->listWidget->currentItem()->text();
        QStringList iport=text.split(':');
        QString ip=iport[0];
        int  port= 8001;
        QTcpSocket *tsocket2=new QTcpSocket();
        tsocket2->connectToHost(ip,port);
        QFile readFile(":/new/prefix1/five.json");
        readFile.open(QIODevice::ReadOnly);
        QByteArray arry;
        while(!readFile.atEnd())
        {
            arry=readFile.read(da.sj.file_len);
            tsocket2->write(arry);
        }
        tsocket2->close();
        QJsonObject json;
        json.insert("type",2);
        QJsonObject item;
        item.insert("flag","stop");
        json.insert("data",QJsonValue(item));
        QJsonDocument document;
        document.setObject(json);
        QByteArray byte_array = document.toJson(QJsonDocument::Compact);
        tsocket->write(byte_array);
    }
    if(da.type==2&&da.sj.flag=="stop")
    {
        //tsocket->close();
        usocket->close();
        QMessageBox::information(this,"Information","连接成功");

    }
    if(da.type==1&&da.up_config==false)
    {
        qDebug()<<"已有点表";
        QMessageBox::information(this,"Information","连接成功");


    }
    if(da.type==3&&da.result==0)
    {
         responseTimer->stop();
         responseTimer->start(6000);

    }
}

Home::~Home()
{
    delete ui;
}


//udp广播
void Home::udpconnect()
{
    QString ip;
    QString text="five";
    QByteArray buffer = text.toUtf8();
    //要改成自动获取ip地址拼接255；
        QString localHostName = QHostInfo::localHostName();
        QHostInfo hostInfo = QHostInfo::fromName(localHostName);
        foreach (QHostAddress address, hostInfo.addresses()) {
           if(address.protocol()==QAbstractSocket::IPv4Protocol)
           {
                qDebug() << "IPv4 Address:" << address.toString();
                ip=address.toString();
                QStringList list=ip.split(".");
                if(list.at(3)!="1")
                {
                    break;
                }

           }

        }
        qDebug()<< ip;
        QStringList list=ip.split(".");
        QString nip=list.at(0)+"."+list.at(1)+"."+list.at(2)+"."+"255";
        qDebug()<< nip;
    usocket->writeDatagram(buffer,QHostAddress(nip),8000);


}
//tcp连接
void Home::tcpconnect()
{
    //tsocket=new QTcpSocket(this);
    QString text=ui->listWidget->currentItem()->text();
    if(text!="")
    {
    QStringList iport=text.split(':');
    QString ip=iport[0];
    int  port= iport[1].toInt();
    tsocket=new QTcpSocket(this);
    tsocket->connectToHost(ip,port);
    QJsonObject json;
    json.insert("type",1);
    QJsonDocument document;
    document.setObject(json);
    QByteArray byte_array = document.toJson(QJsonDocument::Compact);
    tsocket->write(byte_array);
    connect(tsocket,SIGNAL(readyRead()),this,SLOT(tcpread_data()));

    heartbeatTimer->start(5000);
    responseTimer->start(6000);
    qDebug()<<ip<<port;
    }
    else{
        QMessageBox::information(this,"Information","无连接");
    }
}
//读取udp回执信息
void Home::udpread_data()
{
    QHostAddress sender;
    quint16 senderPort;
    QByteArray datagram;
    datagram.resize(int(usocket->pendingDatagramSize()));
    usocket->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
    QString text=datagram.data();
    if(text=="yes")
    {
        QString ip=sender.toString();
        ip.append(":").append("8000");
        qDebug() << "Received:" << ip;
        //正常
        ui->listWidget->addItem(ip);
        //测试
        //ui->listWidget->addItem("192.168.51.135:8879");
    }
    else
    {
        QString text="错误";
        ui->listWidget->addItem(text);
    }

}

void Home::tcpread_data()
{
    QByteArray buffer= tsocket->readAll();
    QString sjson(buffer);
    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(sjson.toLatin1(), &jsonError);
    if (!doucment.isNull() && jsonError.error == QJsonParseError::NoError)
    {
        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            if (doucment.isObject())
            {
                QJsonObject object = doucment.object();
                if (object.contains("type"))
                {  // 包含指定的 key
                    QJsonValue value = object.value("type");
                    if (value.isDouble())
                    {
                        da.type=value.toVariant().toInt();
                        qDebug() << "type : " << da.type;
                    }
                }
                if (object.contains("result"))
                {
                    QJsonValue value = object.value("result");
                    if (value.isDouble())
                    {
                        da.result = value.toVariant().toInt();
                        qDebug() << "result : " << da.result;
                    }
                }
                if (object.contains("up_config"))
                {
                    QJsonValue value = object.value("up_config");
                    if (value.isBool())
                    {
                        da.up_config = value.toBool();
                        qDebug() << "up_config : " << da.up_config;
                    }
                }
                if (object.contains("data"))
                {
                    QJsonValue value = object.value("data");
                    if (value.isObject())
                    {
                        QJsonObject obj = value.toObject();
                        if (obj.contains("flag"))
                        {
                            QJsonValue value = obj.value("flag");
                            if (value.isString())
                            {
                                da.sj.flag = value.toString();
                                qDebug() << "da.sj.flag : " << da.sj.flag;
                            }
                        }
                    }
                }
            }
        }
    }
    xinxijiaohu();
}

void Home::act(QString text)
{
    qDebug() <<text;
    QMQTT::Message message;
    message.setTopic("/app/data/down");
        QJsonObject json;
        json.insert("type",3);
        QJsonObject djson;
        if(text=="变化上报")
        {
            djson.insert("type",1);
        }else if(text=="刷新上报")
        {
            djson.insert("type",0);
        }else if(text=="周期上报")
        {
            djson.insert("type",2);
        }
        djson.insert("period",5);
        json.insert("data",QJsonValue(djson));
        QJsonDocument document;
        document.setObject(json);
        QByteArray byte_array = document.toJson(QJsonDocument::Compact);
        message.setPayload(byte_array);
        GlobalVal ::mqtt->publish(message);

}

void Home::sendHeartbeat()
{
    QJsonObject json;
    json.insert("type",3);
    QJsonDocument document;
    document.setObject(json);
    QByteArray byte_array = document.toJson(QJsonDocument::Compact);
    tsocket->write(byte_array);
}

void Home::onNoResponse()
{
    qDebug() << "tcp连接断开";
    QMessageBox::information(this,"Information","连接断开");
}





